#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bag转换点击处理模块
负责处理Bag文件转换相关的用户交互逻辑
"""

from pathlib import Path
from PySide2.QtWidgets import QFileDialog, QMessageBox
from PySide2.QtCore import QObject, QTimer

from gglobal import logger, config
from mooetoolapp.threadcore.bagchangethread import BagChangeThread
from mooetoolapp.widget.bagchange import BagChangeWindow
from mooetoolapp.handlercore.language_manager import LanguageManager


class BagChangeClickHandler(QObject):
    """
    Bag转换点击处理器
    负责处理Bag文件转换的完整流程
    """
    
    def __init__(self, parent_widget):
        """
        初始化处理器
        
        Args:
            parent_widget: 父窗口部件，用于显示对话框和进度窗口
        """
        super().__init__()
        self.parent_widget = parent_widget
        self.language_manager = LanguageManager()
        self.bag_change_window = None
        self.bag_thread = None
        self._convert_button = None
        self._convert_button_text = None
        
        # 创建进度更新定时器（在主线程中）
        self.progress_timer = QTimer()
        self.progress_timer.timeout.connect(self.update_progress)
        self.progress_timer.setInterval(2000)  # 每2秒更新一次
    
    def handle_bag_convert_clicked(self, sender_button):
        """
        处理Bag转换按钮点击事件
        
        Args:
            sender_button: 触发事件的按钮对象
        """
        logger.info("Bag转换功能被点击")
        
        # 初始化变量
        original_text = None
        
        try:
            # 1. 禁用转换按钮
            if sender_button:
                sender_button.setEnabled(False)
                original_text = sender_button.text()
            
            # 2. 选择输入bag文件
            input_file = self._select_input_file()
            if not input_file:
                # 用户取消选择，重新启用按钮
                if sender_button:
                    sender_button.setEnabled(True)
                return
            
            # 3. 选择输出文件位置
            output_file = self._select_output_file(input_file)
            if not output_file:
                # 用户取消选择，重新启用按钮
                if sender_button:
                    sender_button.setEnabled(True)
                return
            
            # 4. 启动转换流程
            self._start_conversion(input_file, output_file, sender_button, original_text)
            
        except Exception as e:
            logger.error(f"启动Bag转换失败: {e}", exc_info=True)
            QMessageBox.critical(
                self.parent_widget, 
                self.language_manager.get_text("bag_convert_error_title", category="constants"), 
                self.language_manager.get_text("bag_convert_start_failed", category="constants").format(error=str(e))
            )
            # 恢复按钮状态
            if sender_button:
                sender_button.setEnabled(True)
    
    def _select_input_file(self):
        """
        选择输入bag文件
        
        Returns:
            str: 选择的文件路径，如果用户取消则返回None
        """
        input_file, _ = QFileDialog.getOpenFileName(
            self.parent_widget,
            self.language_manager.get_text("bag_convert_select_input", category="constants"),
            "",
            self.language_manager.get_text("bag_convert_file_filter", category="constants")
        )
        return input_file if input_file else None
    
    def _select_output_file(self, input_file):
        """
        选择输出文件位置
        
        Args:
            input_file (str): 输入文件路径
            
        Returns:
            str: 选择的输出文件路径，如果用户取消则返回None
        """
        input_path = Path(input_file)
        default_output = input_path.parent / f"{input_path.stem}_change.bag"
        
        output_file, _ = QFileDialog.getSaveFileName(
            self.parent_widget,
            self.language_manager.get_text("bag_convert_select_output", category="constants"),
            str(default_output),
            self.language_manager.get_text("bag_convert_file_filter", category="constants")
        )
        return output_file if output_file else None
    
    def _start_conversion(self, input_file, output_file, sender_button, original_text):
        """
        启动转换流程
        
        Args:
            input_file (str): 输入文件路径
            output_file (str): 输出文件路径
            sender_button: 触发按钮
            original_text (str): 按钮原始文本
        """
        # 创建并显示转换进度窗口
        self.bag_change_window = BagChangeWindow(self.parent_widget)
        
        # 创建转换线程
        self.bag_thread = BagChangeThread(
            input_bag_path=input_file,
            output_bag_path=output_file,
            target_topics=config.get_param("change_topic"),
        )
        
        # 连接信号
        self.bag_thread.conversion_finished.connect(self.on_conversion_finished)
        self.bag_change_window.cancel_requested.connect(self.on_cancel_conversion)
        
        # 显示进度窗口并启动转换
        self.bag_change_window.show()
        self.bag_thread.start()
        
        # 启动进度定时器
        self.progress_timer.start()
        
        # 保存按钮引用以便后续恢复
        self._convert_button = sender_button
        self._convert_button_text = original_text
    
    def update_progress(self):
        """
        定时器回调函数，获取当前转换进度
        """
        if self.bag_thread and not self.bag_thread.is_cancelled() and self.bag_thread.converter:
            count = self.bag_thread.converter.current_message_count
            if count > 0:
                progress_msg = self.language_manager.get_text("bag_convert_progress_message", category="constants").format(count=count)
                if self.bag_change_window:
                    self.bag_change_window.update_progress(progress_msg)
                logger.info(f"已处理 {count} 条消息")
    
    def on_conversion_finished(self, success, message):
        """
        转换完成处理
        
        Args:
            success (bool): 转换是否成功
            message (str): 转换结果消息
        """
        try:
            # 停止进度定时器
            self.progress_timer.stop()
            
            # 更新进度窗口
            if self.bag_change_window:
                self.bag_change_window.conversion_finished(success, message)
            
            # 显示结果消息
            if success:
                QMessageBox.information(self.parent_widget, self.language_manager.get_text("bag_convert_completed_title", category="constants"), message)
            else:
                QMessageBox.warning(self.parent_widget, self.language_manager.get_text("bag_convert_failed_title", category="constants"), message)
            
            # 恢复转换按钮
            if self._convert_button:
                self._convert_button.setEnabled(True)
                
        except Exception as e:
            logger.error(f"处理转换完成事件失败: {e}", exc_info=True)
    
    def on_cancel_conversion(self):
        """
        取消转换处理
        """
        logger.info("on_cancel_conversion被调用")
        try:
            # 停止进度定时器
            self.progress_timer.stop()
            
            if self.bag_thread:
                logger.info("调用bag_thread.cancel_conversion()")
                self.bag_thread.cancel_conversion()
                logger.info("用户请求取消转换")
            else:
                logger.warning("bag_thread不存在或为None")
        except Exception as e:
            logger.error(f"取消转换失败: {e}", exc_info=True)
    
    def cleanup(self):
        """
        清理资源
        """
        # 停止进度定时器
        if self.progress_timer:
            self.progress_timer.stop()
        
        if self.bag_thread and self.bag_thread.isRunning():
            self.bag_thread.cancel_conversion()
            self.bag_thread.wait()
        
        if self.bag_change_window:
            self.bag_change_window.close()
            self.bag_change_window = None
        
        self.bag_thread = None
        self._convert_button = None
        self._convert_button_text = None